package com.atguigu.yygh.user.controller.user;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.exception.YYGHException;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.result.R;
import com.atguigu.yygh.user.prop.WXProperties;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.utils.HttpClientUtils;
import com.atguigu.yygh.utils.JwtHelper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/*==========================================
      时 间:   2022-04-23
      讲 师:   刘  辉
      描 述:   尚硅谷教学团队
 ==========================================*/
@Controller
@RequestMapping("/api/userinfo/wx")
public class WXController {

    @Autowired
    private WXProperties wxProperties;

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/param")
    @ResponseBody
    public R getWeixinLoginParam(){
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("appid",wxProperties.getAppid());
        stringObjectHashMap.put("scope","snsapi_login");
        stringObjectHashMap.put("redirect_uri",wxProperties.getRedirecturl());
        stringObjectHashMap.put("state", System.currentTimeMillis()+"");
        stringObjectHashMap.put("style","black");
        return R.ok().data(stringObjectHashMap);
    }



    @GetMapping("/callback")
    public String callback(String code,String state) throws Exception {

        StringBuilder stringBuilder=new StringBuilder();
        StringBuilder append = stringBuilder.append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=%s");

        String authorization_code = String.format(append.toString(), wxProperties.getAppid(), wxProperties.getAppsecret(), code, "authorization_code");


        JSONObject jsonObject = JSONObject.parseObject(HttpClientUtils.get(authorization_code));

        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        QueryWrapper<UserInfo> userInfoQueryWrapper=new QueryWrapper<UserInfo>();
        userInfoQueryWrapper.eq("openid", openid);
        UserInfo one = userInfoService.getOne(userInfoQueryWrapper);

        if(one == null){ //首次登录，注册一下
            one=new UserInfo();

            JSONObject jsonObject1 = JSONObject.parseObject(HttpClientUtils.get("https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid));
            one.setOpenid(openid);
            one.setNickName(jsonObject1.getString("nickname"));
            one.setStatus(1);
            userInfoService.save(one);
        }

        //5.验证用户的状态:
        Integer status = one.getStatus();
        if(status == 0){
            throw new YYGHException(20001,"用户已锁定");
        }

        //返回用户信息Map<
        Map<String,String> map = new HashMap<>();

        //如果用户已经绑定了手机号，openid设置为空
        //如果用户没有绑定手机号，openid带到页面去
        if(StringUtils.isEmpty(one.getPhone())){
            map.put("openid",openid);
        }else{
            map.put("openid","");
        }

        String name = one.getName();
        if(StringUtils.isEmpty(name)) {
            name = one.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = one.getPhone();
        }
        map.put("name", name);

        //使用jwt生成token字符串
        String token = JwtHelper.createToken(one.getId(), name);
        map.put("token", token);

        //跳转到前端页面
        return "redirect:http://localhost:3000/weixin/callback?token="+map.get("token")+ "&openid="+map.get("openid")+"&name="+ URLEncoder.encode(map.get("name"),"utf-8");
    }

}
